using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace Gucci.DbTaglio.Site.Features.DbTaglioWebParts
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("ae80efa7-ff2a-40fe-bf46-f4ffa5d275d7")]
    public class DbTaglioWebPartsEventReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                try
                {
                    var site = properties.Feature.Parent as SPSite;
                    if (site == null) return;

                    using (SPWeb web = site.OpenWeb())
                    {
                        //TODO : sistemare nome di dominio... 
                        string domain = Environment.UserDomainName;
                        domain = "WIN-NEBQI3TDPF2";

                        string[] winGroupNameDbTaglioUsers =
                           new[] { domain + @"\DbTaglioUsers", domain + @"\DbTaglioAdmins" };

                        string[] spGroupNameDbTaglioUsers =
                            new[] { "DbTaglioSPUsers", "DbTaglioSPAdmins" };

                        web.AllowUnsafeUpdates = true;

                        AddGroupAndUsers(web, winGroupNameDbTaglioUsers[0], spGroupNameDbTaglioUsers[0], web.RoleDefinitions["Read"],
                            "Users Group for DbTaglio Site");

                        AddGroupAndUsers(web, winGroupNameDbTaglioUsers[1], spGroupNameDbTaglioUsers[1], web.RoleDefinitions["Contribute"],
                            "Admins Group for DbTaglio Site");

                        web.AllowUnsafeUpdates = false;


                    }//end using

                }
                catch (Exception ex)
                {
                    //throw;
                    Microsoft.SharePoint.Administration.SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("DBTaglio",
                    TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                }


                //SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
                //for (int i = SPRoleAssColn.Count -1 ; i >= 0; i--)
                //{
                //    SPRoleAssColn.Remove(i);
                //}
                //Web.RoleAssignments.Add(roleAssignment);


            });


        }//fM

        
        private void AddGroupAndUsers(SPWeb web, string winGroupNameDbTaglio, string spGroupNameDbTaglio, SPRoleDefinition pRoledef, string pDescrizione)
        {

            SPGroup spGroup = null;

            web.AllowUnsafeUpdates = true;
            var existingGroup = containsGroup(web.SiteGroups, spGroupNameDbTaglio);

            if (!existingGroup)
            {
                web.SiteGroups.Add(spGroupNameDbTaglio, web.SiteAdministrators[0], null, pDescrizione);
                web.Update();

                web.AssociatedGroups.Add(web.SiteGroups[spGroupNameDbTaglio]);
                web.Update();

                spGroup = web.SiteGroups[spGroupNameDbTaglio];

                SPRoleAssignment assignment = new SPRoleAssignment(spGroup);
                assignment.RoleDefinitionBindings.Add(pRoledef);
                web.RoleAssignments.Add(assignment);
                //web.BreakRoleInheritance(true);
                web.Update();
            }

            SPUser spUser = web.EnsureUser(winGroupNameDbTaglio);
            if (spUser != null)
            {
                spGroup = web.Groups[spGroupNameDbTaglio];
                if (spGroup != null)
                {
                    spGroup.AddUser(spUser);
                    spGroup.Update();
                }
            }


            web.Update();
        }


        private bool containsGroup(SPGroupCollection pGroupCollection, string pName)
        {
            try
            {
                SPGroup gruppo = pGroupCollection[pName];
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }

        }//fM


    }
}
